<template>
<div :class="['modal', {fade: fade}]" data-backdrop="static" data-disable="false" data-keyboard="true" tabindex="-1">
    <div :class="['modal-dialog', size]">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title text-center text-primary"><span>{{title}}</span></h4>
            </div>
            <div class="modal-body">
                <div class="form-inline" autocomplete="off" spellcheck="false">
                    <div class="form-group form-group-sm">
                        <label>搜索</label>
                        <input type="text" class="form-control" placeholder="关键字" v-model.trim="q" @keydown.enter.prevent ref="q">
                    </div>
                    <span class="hidden-xs">&nbsp;&nbsp;</span>
                    <div class="form-group form-group-sm">
                        <label>轮播间隔(秒)</label>
                        <el-input-number size="mini" placeholder="轮播间隔 (秒)" v-model="interval" :min="10" label="轮播间隔" controls-position="right"></el-input-number>
                    </div>
                    <span class="hidden-xs">&nbsp;&nbsp;</span>
                    <div class="form-group form-group-sm">
                        <div class="checkbox">
                            <el-checkbox style="margin-top:-5px;padding-left:0;" size="small" v-model.trim="related" name="Related">
                                只看已选({{localChannelsAll.length}})
                            </el-checkbox>
                        </div>
                    </div>
                    <div class="form-group form-group-sm pull-right">
                        <button type="button" class="btn btn-primary btn-sm" @click.prevent="startLoopPlay" :disabled="!localChannelsAll || !localChannelsAll.length"><i class="fa fa-play"></i> 开始轮播</button>
                    </div>
                </div>
                <br>
                <el-table :data="related ? localChannels:channels" stripe @sort-change="sortChange" @select="select" @select-all="selectAll" :max-height="500" ref="channelTable" v-loading="loading" element-loading-text="加载中...">
                    <el-table-column type="selection" width="55" fixed :selectable="selectable"></el-table-column>
                    <el-table-column prop="Channel" label="通道号" min-width="90" show-overflow-tooltip sortable="custom" :fixed="!isMobile()"></el-table-column>
                    <el-table-column prop="Name" label="通道名称" min-width="150" :formatter="formatName" show-overflow-tooltip></el-table-column>
                    <el-table-column min-width="200" label="通道快照">
                        <template slot-scope="props">
                            <img onerror="this.src='/images/default_snap.png';" style="height:30px;width:50px;" :src="props.row.SnapURL" v-if="isMobile()">
                            <el-popover placement="left" :title="`[${props.row.Channel}] ${props.row.Name}`" width="300" trigger="hover" v-else>
                                <img onerror="this.src='/images/default_snap.png';" style="width:100%;height:100%;" :src="props.row.SnapURL">
                                <img onerror="this.src='/images/default_snap.png';" style="height:30px;width:50px;" slot="reference" :src="props.row.SnapURL">
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Online" label="在线状态" min-width="90" v-if="!related">
                        <template slot-scope="props">
                            <span v-if="props.row.Online == 1" class="text-primary">在线</span>
                            <span v-else>离线</span>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination v-if="total > 0 && !related" layout="total,prev,pager,next,sizes" :pageSizes="[10, 20, 50, 100, 200]" :pager-count="isMobile() ? 3 : 5" class="pull-right" :total="total" :page-size.sync="pageSize" :current-page.sync="currentPage"></el-pagination>
                <div class="clearfix"></div>
            </div>
            <!-- <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" @click.prevent="startLoopPlay" :disabled="!localChannelsAll || !localChannelsAll.length"><i class="fa fa-play"></i> 开始轮播</button>
            </div> -->
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
</template>

<script>
import _ from 'lodash'
import $ from 'jquery'
import { mapState } from "vuex";
import "jquery-ui/ui/widgets/draggable";

export default {
    props: {
        title: {
            default: '选择轮巡播放通道'
        },
        token: {
            default: ''
        },
        size: {
            type: String,
            default: 'modal-lg'
        },
        fade: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            q: "",
            total: 0,
            pageSize: 10,
            currentPage: 1,
            sort: "",
            order: "",
            loading: false,
            channels: [],
            localData: {
                interval: 10,
                rows: {},
            },
            related: false,
            localChannels: [],
            localChannelsAll: [],
            interval: 10,
        };
    },
    computed: {
        ...mapState(["userInfo", "serverInfo"]),
    },
    watch: {
        q: function (newVal, oldVal) {
            this.doDelaySearch();
        },
        currentPage: function (newVal, oldVal) {
            this.doSearch(newVal);
        },
        pageSize: function (newVal, oldVal) {
            this.doSearch();
        },
        related: function (newVal, oldVal) {
            if (newVal) {
                this.loadLocalChannels();
            } else {
                this.doSearch();
            }
        },
        interval: function (newVal, oldVal) {
            this.localData.interval = newVal;
            this.setLocalData(true);
        },
    },
    mounted() {
        this.loadLocalData();
        $(this.$el).find('.modal-content').draggable({
            handle: '.modal-header',
            cancel: ".modal-title span",
            addClasses: false,
            containment: 'document',
            delay: 100,
            opacity: 0.5
        });
        $(this.$el).on("shown.bs.modal", () => {
            this.$emit("show");
        }).on("hidden.bs.modal", () => {
            this.errors.clear();
            // this.reset();
            this.$emit("hide");
        })
    },
    methods: {
        sortChange(data) {
            this.sort = data.prop;
            this.order = data.order == "ascending" ? "asc" : "desc";
            this.getChannels();
        },
        doSearch(page = 1) {
            this.currentPage = page;
            if (this.related) {
                this.loadLocalChannels();
            } else {
                this.getChannels();
            }
        },
        doDelaySearch: _.debounce(function () {
            this.doSearch();
        }, 500),
        formatName(row, col, cell) {
            return row.CustomName || row.Name || "-";
        },
        formatManufacturer(row, col, cell) {
            if (cell) return cell;
            return "-";
        },
        getChannels() {
            this.loading = true;
            var param = {
                q: this.q,
                online: true,
                start: (this.currentPage - 1) * this.pageSize,
                limit: this.pageSize,
                sort: this.sort,
                order: this.order
            }
            if (this.token) {
                param.token = this.token;
            }
            $.get("/api/v1/getchannels", param).then(ret => {
                this.$refs["channelTable"].clearSelection();
                this.total = (ret.LiveQing || ret.NVR).Body.ChannelCount || 0;
                this.channels = (ret.LiveQing || ret.NVR).Body.Channels || [];
                this.$nextTick(() => {
                    this.channels.forEach(row => {
                        if (this.localData.rows[row.Channel]) {
                            this.localData.rows[row.Channel] = row;
                            this.$refs["channelTable"].toggleRowSelection(row);
                        }
                    })
                    this.setLocalData(false);
                })
            }).always(() => {
                this.$nextTick(() => {
                    this.loading = false;
                })
            });
        },
        // rowClick(row, event, column) {
        //     if (!row) {
        //         return
        //     }
        //     if (this.localData.rows[row.Channel]) {
        //         delete this.localData.rows[row.Channel];
        //     } else {
        //         this.localData.rows[row.Channel] = row;
        //     }
        //     this.$refs["channelTable"].toggleRowSelection(row);
        //     this.setLocalData(false);
        // },
        // rowStyle({row, rowIndex}) {
        //     if (row.Online == 1) {
        //         return "cursor:pointer";
        //     }
        //     return "";
        // },
        reset() {
            this.channels = [];
            this.q = "";
            this.currentPage = 1;
            this.pageSize = 10;
        },
        show() {
            $(this.$el).modal("show");
            if (this.related) {
                this.loadLocalData()
            } else {
                this.getChannels();
            }
        },
        hide() {
            $(this.$el).modal("hide");
        },
        selectable(row, index) {
            return true;
        },
        select(selection, row) {
            var r = this.localData.rows[row.Channel] || "";
            var idx = selection.indexOf(row);
            if (idx >= 0) {
                if (!r) {
                    this.localData.rows[row.Channel] = row;
                }
            } else {
                if (r) {
                    delete this.localData.rows[row.Channel];
                }
            }
            this.setLocalData();
        },
        selectAll(selection) {
            if (selection.length) {
                this.selection = selection;
                for (var row of selection) {
                    var r = this.localData.rows[row.Channel] || "";
                    if (!r) {
                        this.localData.rows[row.Channel] = row;
                    }
                }
            } else {
                if (this.related) {
                    for (var row of this.localChannels) {
                        var r = this.localData.rows[row.Channel] || "";
                        if (r) {
                            delete this.localData.rows[row.Channel];
                        }
                    }
                } else {
                    for (var row of this.channels) {
                        var r = this.localData.rows[row.Channel] || "";
                        if (r) {
                            delete this.localData.rows[row.Channel];
                        }
                    }
                }
            }
            this.setLocalData();
        },
        setLocalData(updateSet) {
            localStorage['livenvr_screen_loop_play'] = JSON.stringify(this.localData);
            if (!updateSet) {
                this.loadLocalChannels();
            }
        },
        loadLocalData() {
            if (localStorage['livenvr_screen_loop_play']) {
                this.localData = JSON.parse(localStorage['livenvr_screen_loop_play']);
                this.interval = this.localData.interval;
                this.loadLocalChannels();
            }
        },
        async loadLocalChannels() {
            var localRows = [];
            var localRowsAll = [];
            for (var key in this.localData.rows) {
                var r = this.localData.rows[key];
                if(!r) {
                    delete this.localData.rows[key];
                    continue
                }
                if (!this.hasAllChannel(this.serverInfo, this.userInfo)) {
                    var ok = await this.hasChannel(r.Channel);
                    if(!ok) {
                        delete this.localData.rows[key];
                        continue
                    }
                }
                localRowsAll.push(r);
                if (!this.q) {
                    localRows.push(r);
                } else {
                    if ((r.Name.indexOf(this.q) != -1 || (r.Channel + "").indexOf(this.q) != -1)) {
                        localRows.push(r);
                    }
                }
            }
            this.localChannelsAll = localRowsAll;
            this.localChannels = localRows;
            if (this.related) {
                this.$nextTick(() => {
                    this.localChannels.forEach(row => {
                        this.$refs["channelTable"].toggleRowSelection(row);
                    })
                })
            }
        },
        hasChannel(channel) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    method: "GET",
                    url: "/api/v1/getchannels",
                    global: false,
                    data: {
                        channel: channel,
                    }
                }).then(data => {
                    try {
                        var cc = (data.LiveQing || data.NVR).Body.ChannelCount || 0;
                        if(cc > 0) {
                            resolve(true);
                            return
                        }
                    } catch(err) {}
                    resolve(false);
                }).fail(xhr => {
                    resolve(false);
                })
            })
        },
        startLoopPlay() {
            if (!this.localChannelsAll || !this.localChannelsAll.length) {
                this.$message({
                    type: "warning",
                    message: "请选择需要轮巡播放的通道"
                })
                return
            }
            this.$emit("loopPlay", this.localChannelsAll, this.interval);
            this.hide();
        },
    }
};
</script>
